package com.xjd.edu.toolkit.helper;

import cn.hutool.core.lang.Assert;
import com.xjd.edu.toolkit.cache.GameRedisTemplate;
import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.NotNull;
import java.time.Duration;

/**
 * 幂等方法辅助类
 *
 * @author wangyu
 * @created 2025/3/15 15:27
 */
@Slf4j
public final class IdempotentHelper {

    private GameRedisTemplate gameRedisTemplate;

    public IdempotentHelper(GameRedisTemplate gameRedisTemplate) {
        Assert.notNull(gameRedisTemplate, "GameRedisTemplate 参数不能为空");
        this.gameRedisTemplate = gameRedisTemplate;
    }

    /**
     * 幂等控制，实际通过 Redis 命令 SETNX key value 实现
     *
     * @param key
     * @param timeout
     * @return
     */
    public boolean idempotent(@NotNull String key, @NotNull Duration timeout) {
        try {
            return gameRedisTemplate.setnx(key, timeout);
        } catch (Exception e) {
            log.error("执行幂等操作出错", e);
            return false;
        }
    }

    /**
     * 取消幂等
     *
     * @param key
     */
    public void cancel(@NotNull String key) {
        gameRedisTemplate.del(key);
    }

    /**
     * 默认5分钟超时
     *
     * @param key
     * @return
     * @see #idempotent(String, Duration)
     */
    public boolean idempotent(@NotNull String key) {
        return idempotent(key, Duration.ofMinutes(5));
    }

}
